"""The functions to read and write the data used in the program

Written by Nikhil Murthy"""

import json

def loadProfiles(profileFile):
    """Loads a set of profiles from a JSON file"""
    profiles=loadFromJson(profileFile)
    profiles=dict((name, loadProfile(fil))
                  for name, fil in profiles.iteritems())
    return profiles

def loadFromJson(fil):
    """Loads the lists of elements from a JSON file"""
    try:
        with open(fil) as inStream:
            return json.loads(inStream.read())
    except IOError:
        return [] #Default if the file will not load

def loadProfile(fil):
    """Loads the profile from a JSON file"""
    profileDetails=loadFromJson(fil)
    elementFile, atts, baseDir, uniqueAtts=(profileDetails[i] for i in
                             ('elements','atts','baseDir', 'uniqueAtts'))
    try:
        return Profile(loadFromJson(elementFile), atts, baseDir, uniqueAtts,
                       elementFile)
    except IOError:
        print fil
        raise IOError

class Profile(object):
    """To store everything that is specific to the current user"""
    def __init__(self, elements, atts, baseDir, uniqueAtts=None,
                 elementFile=None):
        if not elements:
            raise IOError
        if uniqueAtts is None:
            uniqueAtts=atts
        self.elements=elements
        self.atts=atts
        self.baseDir=baseDir
        self.uniqueAtts=uniqueAtts
        self.elementFile=elementFile
    def save(self):
        if self.elementFile:
            with open(self.elementFile, 'w') as outStream:
                outStream.write(json.dumps(self.elements, indent=1))

def loadPlaylists(fil):
    """Loads a playlist from a file"""
    return [Playlist(**playlistDetails) for playlistDetails
            in loadFromJson(fil)]

class Playlist(object):
    """Playlists to hold only selected items. Contains its name and all that
    is needed to determine if an item is part of it"""
    #The below are all None so as allow keyword expansions
    def __init__(self, name=None, logic=None, items=None, blacklist=None):
        self.name=name
        self.logic=logic
        self.items=items
        self.blacklist=blacklist
